package com.smscrypt;

import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;

   /**
   * This program generates a AES key, retrieves its raw bytes, and
   * then reinstantiates a AES key from the key bytes.
   * The reinstantiated key is used to initialize a AES cipher for
   * encryption and decryption.
   */

   public class RC4 {

     /**
     * Turns array of bytes into string
     *
     * @param buf	Array of bytes to convert to hex string
     * @return	Generated hex string
     */
     public static String asHex (byte buf[]) {
      StringBuffer strbuf = new StringBuffer(buf.length * 2);
      int i;

      for (i = 0; i < buf.length; i++) {
       if (((int) buf[i] & 0xff) < 0x10)
	    strbuf.append("0");

       strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
      }

      return strbuf.toString();
     }
     
     public final byte[] encrypt(String decrypted, SecretKey skey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
    	 byte[] raw = skey.getEncoded();
    	 SecretKeySpec skeySpec = new SecretKeySpec(raw, "RC4");	
    	 Cipher cipher = Cipher.getInstance("RC4");
    	 cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    	 
    	 return cipher.doFinal(decrypted.getBytes());
     }
     
     public final String decrypt(byte[] encrypted, SecretKey skey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
    	 byte[] raw = skey.getEncoded();
    	 SecretKeySpec skeySpec = new SecretKeySpec(raw, "RC4");
    	 Cipher cipher = Cipher.getInstance("RC4");
    	 cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    	 
    	 return new String(cipher.doFinal(encrypted));    	 
     }
     
     public final SecretKey genKey() throws NoSuchAlgorithmException{
    	 // Get the KeyGenerator
         KeyGenerator kgen = KeyGenerator.getInstance("RC4");
         kgen.init(128); // 192 and 256 bits may not be available


         // Generate the secret key specs.
         SecretKey skey = kgen.generateKey();
         return skey;
     }     
   }